package com.winai.launcher.view.set;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.winai.launcher.R;
import com.winai.launcher.adapter.ScanDeviceAdapter;
import com.winai.launcher.base.BaseActivity;
import com.winai.launcher.bean.BleRssiDevice;
import com.winai.launcher.interfaces.ScanCallBack;
import com.winai.launcher.manager.AysDeviceManager;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.com.heaton.blelibrary.ble.model.BleDevice;
import cn.com.heaton.blelibrary.ble.model.ScanRecord;
import cn.com.heaton.blelibrary.ble.utils.BleUtils;

public class AysDeviceActivity extends BaseActivity {

    @BindView(R.id.str_title)
    TextView strTitle;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.floatingButton)
    FloatingActionButton floatingActionButton;

    private String TAG = AysDeviceActivity.class.getSimpleName();
    private ScanDeviceAdapter adapter;
    public static final int REQUEST_GPS = 4;
    private Context mContext = this;
    private ObjectAnimator animator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ays_device);
        ButterKnife.bind(this);
        strTitle.setText("我的设备");
        start();
    }

    private void start() {
        initObject();
        initListener();
        checkGpsStatus();
    }

    private void initObject() {
        adapter = new ScanDeviceAdapter(this, AysDeviceManager.getInstance(mContext).getBleRssiDevices());
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        recyclerView.getItemAnimator().setChangeDuration(0);
        recyclerView.getItemAnimator().setMoveDuration(0);
        recyclerView.setAdapter(adapter);
    }

    private void initListener() {
        adapter.setOnItemClickListener((parent, view, bleRssiDevice, position) -> {
            AysDeviceManager.getInstance(mContext).stopScan();
            startActivity(new Intent(
                    AysDeviceActivity.this,
                    DeviceControlActivity.class)
                    .putExtra(DeviceControlActivity.EXTRA_TAG, bleRssiDevice.getDevice()));
        });
    }

    //检查蓝牙是否支持及打开
    private void checkGpsStatus() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                && !BleUtils.isGpsOpen(AysDeviceActivity.this)) {
            new AlertDialog.Builder(AysDeviceActivity.this)
                    .setTitle("提示")
                    .setMessage("为了更精确的扫描到Bluetooth LE设备,请打开GPS定位")
                    .setPositiveButton("确定", (dialog, which) -> {
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivityForResult(intent, REQUEST_GPS);
                    })
                    .setNegativeButton("取消", null)
                    .create()
                    .show();
        } else {
            AysDeviceManager.getInstance(AysDeviceActivity.this).startScan(scanCallBack);
//            AysDeviceManager.getInstance(mContext).startConnect("38:D2:CA:39:5D:1C", null);
        }
    }

    private ScanCallBack scanCallBack = new ScanCallBack() {
        @Override
        public void onLeScan(BleDevice device, int rssi, byte[] scanRecord) {
            if (TextUtils.isEmpty(device.getBleAddress())) return;
            synchronized (AysDeviceManager.getInstance(mContext).getBle().getLocker()) {
                Log.e(TAG, "onLeScan: " + device.getBleAddress() + ";name = " + device.getBleName());
                for (int i = 0; i < AysDeviceManager.getInstance(mContext).getBleRssiDevices().size(); i++) {
                    BleRssiDevice rssiDevice = AysDeviceManager.getInstance(mContext).getBleRssiDevices().get(i);
                    BleDevice bleDevice = rssiDevice.getDevice();
                    if (TextUtils.equals(bleDevice.getBleAddress(), device.getBleAddress())) {
                        if (rssiDevice.getRssi() != rssi && System.currentTimeMillis() - rssiDevice.getRssiUpdateTime() > 1000L) {
                            rssiDevice.setRssiUpdateTime(System.currentTimeMillis());
                            rssiDevice.setRssi(rssi);
                            adapter.notifyItemChanged(i);
                        }
                        return;
                    }
                }
                if (device.getBleAddress() != null && device.getBleAddress().contains("38:D2:CA:39:5D")) {
                    BleRssiDevice rssiDevice = new BleRssiDevice(device, ScanRecord.parseFromBytes(scanRecord), rssi);
                    AysDeviceManager.getInstance(mContext).getBleRssiDevices().add(rssiDevice);
                    adapter.notifyDataSetChanged();
                }
            }
        }

        @Override
        public void onStart() {
            startBannerLoadingAnim();
        }

        @Override
        public void onStop() {
            stopBannerLoadingAnim();
        }
    };

    public void startBannerLoadingAnim() {
        floatingActionButton.setImageResource(R.drawable.ic_loading);
        animator = ObjectAnimator.ofFloat(floatingActionButton, "rotation", 0, 360);
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.setDuration(800);
        animator.setInterpolator(new LinearInterpolator());
        animator.start();
    }

    public void stopBannerLoadingAnim() {
        floatingActionButton.setImageResource(R.drawable.ic_bluetooth_audio_black_24dp);
        animator.cancel();
        floatingActionButton.setRotation(0);
    }

    @Override
    protected void onPause() {
        super.onPause();
        AysDeviceManager.getInstance(mContext).stopScan();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AysDeviceManager.getInstance(mContext).getBle().disconnectAll();
    }

    @OnClick({R.id.iv_back, R.id.iv_home, R.id.floatingButton})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_home:
                //模拟HOME
                Intent it = new Intent(Intent.ACTION_MAIN);
                it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                it.addCategory(Intent.CATEGORY_HOME);
                startActivity(it);
                break;
            case R.id.floatingButton:
                AysDeviceManager.getInstance(mContext).startScan(scanCallBack);
                break;
        }
    }
}